package core.rdd.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;

import java.util.Arrays;
import java.util.List;

public class Spark06_GROUPBY2 {
    public static void main(String[] args) {
        /**
         *flatMap 是将多集合转换成一个
         */
        // 配置SparkConf指向你的Spark master URL
        SparkConf conf = new SparkConf()
                .setAppName("Spark05_GROUPBY2") // 应用名称
                .setMaster("local[*]"); // 替换成你的master地址
        JavaSparkContext sc = new JavaSparkContext(conf);
        // 创建JavaSparkContext，它是与集群交互的主要入口点
        try {

//            List<List<String>> stringLists = Arrays.asList(
//                    Arrays.asList("张三", "张四", "张5", "张6")
//                    , Arrays.asList("王三", "王四", "王5", "王6")
//                    , Arrays.asList("杨1", "杨12", "杨123", "杨1234"));
            List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6);
            JavaRDD<Integer> parallelize = sc.parallelize(integers, 3);

            parallelize.saveAsTextFile("out1");
            int numPartitions = parallelize.getNumPartitions();
            System.out.println(numPartitions);



            /**
             * 非省略写法
             */

            JavaPairRDD<Object, Iterable<Integer>> objectIterableJavaPairRDD = parallelize.groupBy(new Function<Integer, Object>() {
                @Override
                public Object call(Integer v1) throws Exception {
                    return v1 % 2 == 0;
                }
            });

            objectIterableJavaPairRDD.saveAsTextFile("out2");
            System.out.println(objectIterableJavaPairRDD.getNumPartitions());


            objectIterableJavaPairRDD.collect().forEach(System.out::println);

        } finally {
            sc.close();
        }
    }
}

